// utils/storageManager.js
// 存储管理工具类

class StorageManager {
  constructor() {
    this.REMINDERS_KEY = 'reminders';
  }

  // 获取所有提醒
  getReminders() {
    try {
      return wx.getStorageSync(this.REMINDERS_KEY) || [];
    } catch (error) {
      console.error('获取提醒列表失败', error);
      return [];
    }
  }

  // 保存提醒列表
  saveReminders(reminders) {
    try {
      wx.setStorageSync(this.REMINDERS_KEY, reminders);
      return true;
    } catch (error) {
      console.error('保存提醒列表失败', error);
      return false;
    }
  }

  // 添加新提醒
  addReminder(reminderData) {
    const reminders = this.getReminders();
    const newReminder = {
      id: Date.now(),
      ...reminderData,
      isActive: true,
      createdAt: new Date().toISOString()
    };
    
    reminders.push(newReminder);
    const success = this.saveReminders(reminders);
    
    return success ? newReminder : null;
  }

  // 更新提醒
  updateReminder(id, updates) {
    const reminders = this.getReminders();
    const index = reminders.findIndex(r => r.id === id);
    
    if (index === -1) return false;
    
    reminders[index] = { ...reminders[index], ...updates };
    return this.saveReminders(reminders);
  }

  // 删除提醒
  deleteReminder(id) {
    const reminders = this.getReminders();
    const filteredReminders = reminders.filter(r => r.id !== id);
    return this.saveReminders(filteredReminders);
  }

  // 切换提醒状态
  toggleReminderStatus(id) {
    const reminders = this.getReminders();
    const reminder = reminders.find(r => r.id === id);
    
    if (!reminder) return false;
    
    return this.updateReminder(id, { isActive: !reminder.isActive });
  }

  // 获取活跃的提醒
  getActiveReminders() {
    return this.getReminders().filter(r => r.isActive);
  }

  // 保存音频文件
  saveAudioFile(tempPath) {
    return new Promise((resolve, reject) => {
      const fileName = `audio_${Date.now()}.mp3`;
      const savedPath = `${wx.env.USER_DATA_PATH}/${fileName}`;
      
      wx.getFileSystemManager().copyFile({
        srcPath: tempPath,
        destPath: savedPath,
        success: () => resolve(savedPath),
        fail: reject
      });
    });
  }

  // 删除音频文件
  deleteAudioFile(filePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().unlink({
        filePath,
        success: resolve,
        fail: reject
      });
    });
  }

  // 清理无效的音频文件
  cleanupAudioFiles() {
    const reminders = this.getReminders();
    const validPaths = reminders.map(r => r.audioPath);
    
    // 获取用户数据目录下的所有音频文件
    wx.getFileSystemManager().readdir({
      dirPath: wx.env.USER_DATA_PATH,
      success: (res) => {
        res.files.forEach(fileName => {
          if (fileName.startsWith('audio_') && fileName.endsWith('.mp3')) {
            const fullPath = `${wx.env.USER_DATA_PATH}/${fileName}`;
            if (!validPaths.includes(fullPath)) {
              this.deleteAudioFile(fullPath).catch(console.error);
            }
          }
        });
      },
      fail: console.error
    });
  }
}

module.exports = StorageManager;